package com.football;

import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
//import android.view.Menu;
//import android.view.MenuInflater;
//import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;

public class HomeActivity extends Activity {

	private static final String LOGTAG = "Football";
	
	// label KEYS used to transfer parameters between activities
	public static final String XML_ARRAY = "xml_array";
	
	// label KEYS used to read XML files
	private static final String XML_FOOTBALL_TOPIC = "footballTopic";
	private static final String XML_NAME = "name";
	private static final String XML_TYPE = "type";
	private static final String XML_VIDEO_URL = "videoURL";
	private static final String XML_VIDEO_NAME = "videoName";
	private static final String XML_MY_VIDEO_NAME = "myVideoName";	

	private ArrayList<FootballTopic> aFootballTopics;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        aFootballTopics = new ArrayList<FootballTopic>();
        if (loadFootballTopics()) {
    	    FootballApp appState = ((FootballApp)getApplicationContext());
    	    appState.setFootballTopics(aFootballTopics); //Better than a global variable
        }
        
    	if (!hasWifiConnection()) {
    		showAlertActivateWifi();  // Ask for the activation of a WIFI network
    	}
		
		/* AdMob Publicity */ 
	    // Lookup R.layout.main
	    LinearLayout layout = (LinearLayout)findViewById(R.id.MainAdMob);
	    // Create the adView
	    // AdMob jgilrincon Publisher ID:  a14e0fa8bd52ff2
	    AdView adView = new AdView(this, AdSize.BANNER, "a14e0fa8bd52ff2");
	    // Add the adView to it
	    layout.addView(adView);
	    // Initiate a generic request to load it with an ad
	    AdRequest request = new AdRequest();
	    request.setTesting(true);
	    adView.loadAd(request);      	
    }
    
    public void onDribblingClick(View v) {
    	ArrayList<String> aList = getFootballTopicsList("technique_dribbling");
    	Intent intent = new Intent(this, TopicsListActivity.class);
    	intent.putExtra(XML_ARRAY, aList);
        startActivity(intent);
    }
    
    public void onChutesClick(View v) {
    	ArrayList<String> aList = getFootballTopicsList("technique_chutes");
    	Intent intent = new Intent(this, TopicsListActivity.class);
    	intent.putExtra(XML_ARRAY, aList);
        startActivity(intent);
    }
    
    public void onDrivingClick(View v) {
    	ArrayList<String> aList = getFootballTopicsList("technique_driving");
    	Intent intent = new Intent(this, TopicsListActivity.class);
    	intent.putExtra(XML_ARRAY, aList);
        startActivity(intent);
    }
    
    public void onOthersClick(View v) {
    	ArrayList<String> aList = getFootballTopicsList("technique_others");
    	Intent intent = new Intent(this, TopicsListActivity.class);
    	intent.putExtra(XML_ARRAY, aList);
        startActivity(intent);
    }
    
	// Keep and save footballTopics from xml
    private boolean loadFootballTopics(){
        boolean bReturn = true; // return value
    	XmlPullParser parser = getResources().getXml(R.xml.football_topics); // XML parser
         
        try {
            while (parser.next() != XmlPullParser.END_DOCUMENT) {
                String mainTag = parser.getName();
                String name = null;
                String type = null;
                String videoURL = null;
                String videoName = null;
                String myVideoName = null;
                if ((mainTag != null) && mainTag.equals(XML_FOOTBALL_TOPIC)) {
                    int size = parser.getAttributeCount();
                    for (int i = 0; i < size; i++) {
                        String attrName = parser.getAttributeName(i);
                        String attrValue = parser.getAttributeValue(i);
                        if ((attrName != null) && attrName.equals(XML_NAME)) {
                            name = attrValue;
                        } else if ((attrName != null) && attrName.equals(XML_TYPE)) {
                            type = attrValue;
                        } else if ((attrName != null) && attrName.equals(XML_VIDEO_URL)) {
                            videoURL = attrValue;
                        } else if ((attrName != null) && attrName.equals(XML_VIDEO_NAME)) {
                            videoName = attrValue;
                        } else if ((attrName != null) && attrName.equals(XML_MY_VIDEO_NAME)) {
                            myVideoName = attrValue;
                        }
                    }
                    if ((name != null) && (type != null) && (videoURL != null) && (videoName != null) && (myVideoName != null)) {
                    	aFootballTopics.add(new FootballTopic( getString(getResources().getIdentifier(name, "string", "com.football")),type,videoURL,videoName,myVideoName));
                    }
                }                
            }            
        } catch (Exception e) { // Error
            Log.e(HomeActivity.LOGTAG, e.getMessage(), e);
            bReturn = false; 
        }  
        return bReturn;
    }
    
    // Get the ArrayLists of a specific FootballTopic type
    private ArrayList<String> getFootballTopicsList(String type){
    	ArrayList<String> aFootballTopicsList = new ArrayList<String>();
    	FootballTopic footballTopic = null;
    	for (int i=0; i<aFootballTopics.size(); i++){
    		footballTopic = aFootballTopics.get(i);
    		if (footballTopic.getType().equals(type)) {
    			aFootballTopicsList.add(footballTopic.getName());
    		}    		
    	}
    	return aFootballTopicsList;
    }

    /*
    // Inflates the menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    // Handle the context menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.settings:
    		Intent intentSettings = new Intent().setClass(this, SettingsActivity.class);
    		startActivity(intentSettings);
            return true;
        case R.id.about:
    		Intent intentAbout = new Intent().setClass(this, AboutActivity.class);
    		startActivity(intentAbout);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    } 
     */
    
    public boolean hasWifiConnection()
    {
        boolean hasWifiConnection = false;

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo)
        {
            if ("WIFI".equals(ni.getTypeName()) & ni.isConnected())
                    hasWifiConnection = true;
        }
        return hasWifiConnection;
    }    

    public void showAlertActivateWifi()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getString(R.string.noWifiConnection))
               .setCancelable(false)
               .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                	   startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
                   }
               })
               .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                	   //showYouTubeVideo();
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();
    }    
}